#include <time.h>
#include "Socket.hpp"
#include "Protocol.hpp"
using namespace socket_ns;
using namespace protocol_ns;

void Useage(const std::string &s)
{
    std::cout << "Useage" << ":\n\t" << " ip port\n";
}

const static std::string opers = "+-*/%^&|";

class Factory
{
public:
    Factory()
    {
        srand(time(nullptr));
    }
    static Request CreateRequest()
    {
        int x = rand() % 20 + 1;
        int y = rand() % 10;
        char oper = opers[rand() % opers.size()];

        Request req(x, y, oper);
        return req;
    }
    ~Factory()
    {
    }
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Useage(argv[0]);
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    std::unique_ptr<Socket> tsvr = std::make_unique<TcpSocket>();
    INetAddr peer(ip, port);

    bool r = tsvr->BuildClient(peer);

    std::string inbuffer;

    while (r)
    {
        sleep(2);
        Request req = Factory::CreateRequest();

        // 1. 序列化数据
        std::string send_message;
        req.Serialize(send_message);
        std::cout << "send request 序列化 : " << send_message << std::endl;

        // 2. 添加报头字段
        send_message = EnCode(send_message);
        std::cout << "send request 报文 : " << send_message;

        // 3.发送给服务器
        tsvr->Send(send_message);

        // 4. 从服务器接收结果数据
        int n = tsvr->Recv(inbuffer);
        if (n < 0)
            break;

        // 5.判断是否构成完整的报文
        std::string message = DeCode(inbuffer);
        // 不构成完整的报文就继续读取报文
        if (message == "")
            continue;

        Response res;
        res.DeSerialize(message);

        std::cout << "recv response message : "<< res._result << "[" << res._code << "]" << std::endl;
        sleep(1);
    }

    return 0;
}